import requests
from requests import Response
import xmltodict

from untils.log_ import logger

base_url = "http://ihrm2-test.itheima.net"


class BaseApi(object):
    def __init__(self, base_url):
        """
        初始化
        :param base_url:
        """

        self.base_url = base_url
        self.token = self.__get_token()
        self.requests = requests.Session()

    def send(self, **kwargs):
        """
        发送请求
        :param kwargs:
        :return:
        """
        url = self.base_url + kwargs["url"]
        logger.error(f"{kwargs}")
        kwargs.pop("url")
        return self.__common_json(self.requests.request(**kwargs, headers=self.__set_header(), url=url))

    def __common_json(self, response: Response):
        """
        返回json格式
        :return:
        """
        text = response.text
        try:
            if text.startswith("<!DOCTYPE html>"):
                final_text = xmltodict.parse(text)
            elif text.startswith("<?xml"):
                final_text = xmltodict.parse(text)
            else:
                final_text = response.json()
        except Exception as e:
            logger.error(f"响应体转换json失败：{e}")
            raise "响应体转换json失败"

        return final_text

    def __get_token(self):
        """
        获取token
        :return:
        """
        url = self.base_url + "/api/sys/login"
        data = {"mobile": "13800000002", "password": "123456"}
        headers = {"Content-Type": "application/json"}
        response = requests.post(url=url, json=data, headers=headers)
        if response.json().get("data"):
            token = response.json().get("data")
        else:
            token = None
        logger.debug(f"token:{token}")
        return token

    def __set_header(self):
        """
        设置请求头
        :return:
        """
        headers = {
            "Content-Type": "application/json",
            "Authorization": self.token,
        }
        return headers

    def __common_assert(self):

        pass


if __name__ == '__main__':
    test_data = {"method": "post", "url": "/api/sys/user",
                 "json": {"username": "caomei", "mobile": "15565161664", "workNumber": "09876"}}
    base_api = BaseApi(base_url)
    print(base_api.send(**test_data))
